<template>
  <div class="article-comments">
    <!-- 评论列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell
        v-for="item in list"
        :key="item.com_id"
      >
        <van-image
          slot="icon"
          round
          width="30"
          height="30"
          style="margin-right: 10px;"
          :src="item.aut_photo"
        />
        <span style="color: #466b9d;" slot="title">{{item.aut_name}}</span>
        <div slot="label">
          <p style="color: #363636;">{{item.content}}</p>
          <p>
            <span style="margin-right: 10px;">{{item.pubdate|relative}}</span>
            <van-button @click="clickShowReply(item)" size="mini" type="default">回复</van-button>
          </p>
        </div>
        <van-icon slot="right-icon" name="like-o" />
      </van-cell>
    </van-list>
    <!-- 评论列表 -->
<!-- 回复评论模块 -->
<van-popup v-model="show" round position="bottom"  closeable
  close-icon-position="top-left" :style="{ height: '85%' }">
  <comment-reply :comment="currentComment" :article-id="id"></comment-reply>
</van-popup>
<!-- 回复评论模块 -->

    <!-- 发布评论 -->
    <van-cell-group class="publish-wrap">
      <van-field
        clearable
        placeholder="请输入评论内容"
        v-model="content"
      >
        <van-button slot="button" size="mini" type="info" @click="addComment">发布</van-button>
      </van-field>
    </van-cell-group>
    <!-- /发布评论 -->
  </div>
</template>

<script>
import CommentReply from './commentReply.vue'
import { reqGetComment, reqAddComment } from '@/api/comment'
export default {
  name: 'ArticleComment',
  components: { CommentReply },
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      content: '',
      offset: '',
      show: false,
      currentComment: {}
    }
  },

  methods: {
    async onLoad () {
      // 异步更新数据
      const res = await reqGetComment(this.id, 'a', this.offset)
      this.list = [...this.list, ...res.data.results]
      this.loading = false
      if (res.data.results.length === 0) this.finished = true
      this.offset = res.data.last_id
    },
    async addComment () {
      const res = await reqAddComment(this.id, this.content)
      this.list.unshift(res.data.new_obj)
      this.content = ''
      this.$toast.success('发布评论成功')
    },
    clickShowReply (item) {
      // 1. 展示回复组件
      this.show = true
      // 2. 更新正在回复的组件
      this.currentComment = item
    }
  }
}
</script>

<style scoped lang='scss'>
// 发表评论的区域是固定在下端的
.publish-wrap {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
}
// 给发表评论区空出地方
.van-list {
  margin-bottom: 45px;
}
</style>
